package org.openems.osa;

import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import org.openems.entity.ChoiceEntity;
import org.openems.entity.Entity;
import org.openems.entity.Key;

import framework.DomainService;
import framework.EntityStoreListener;

public class MyComboBox {
	private IComboBox combo;
	private ChoiceEntity choiceEntity;
	private ItemListener itemListener;
	private IPanel panel;
	
	public MyComboBox(Key key, final DomainService service, IComboBox comboBox) {
		this.combo = comboBox;
		service.addEntityStoreListener(new EntityStoreListener() {
			@Override
			public void valueChanged(Entity entity) {
				choiceEntity = (ChoiceEntity)entity;
				updateValue();
			}
		}, key);
		
		choiceEntity = (ChoiceEntity)service.getEntity(key);
		updateValue();
		
		itemListener = new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent event) {
				if (event.getStateChange() == ItemEvent.SELECTED) {
					//Object item = event.getItem();
					choiceEntity.setIndex(combo.getSelectedIndex());
					service.putEntity(choiceEntity);
				}
			}
		};
		combo.addItemListener(itemListener);
		
		panel = new SwingPanel();
		panel.setLayout(new FlowLayout());
		//panel.add(new JLabel(choiceEntity.getName()));
		panel.add(combo);
	}

	public IPanel getComponent() {
		return panel;
	}

	private void updateValue() {
		combo.removeItemListener(itemListener);
		combo.removeAllItems();
		for (String s : choiceEntity.getChoices()) {
			combo.addItem(s);
		}
		combo.setSelectedIndex(choiceEntity.getIndex());
		combo.addItemListener(itemListener);
	}
	
}
